package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.UniversalServiceClient;
import com.hxkj.domain.po.SiteUniversal;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_SITEINFO;

/**
 * 获取站点信息
 */
@Component
public class SiteInfoDirective extends AbstractDirective {

    /**
     * 站点ID。
     */
    private static final String SITE_ID = "siteId";

    @Autowired
    private UniversalServiceClient universalServiceClient;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            Long siteId = getLong(SITE_ID, params) == null ? (Long) super.getCustomAttrbute(env, SITE_ID) : getLong(SITE_ID, params);
            SiteUniversal siteUniversal_ = new SiteUniversal();
            siteUniversal_.setSiteId(siteId);
            SiteUniversal siteUniversal = universalServiceClient.get(siteUniversal_).getData();
            env.setVariable("siteUniversal", DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(siteUniversal));
            String note = super.getNote(env);
            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_SITEINFO, "");
                    maps.put(SITE_ID, String.valueOf(getLong(SITE_ID, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("站点信息所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
